package com.springboot.ww.platform.pd.util;

import com.springboot.ww.platform.pd.lms.api.PddCommonDTO;
import com.ww.springboot.boot.utils.json.JsonUtil;
import com.ww.springboot.boot.utils.Func;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.TreeMap;

import static cn.hutool.core.util.ClassUtil.isSimpleValueType;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-05-09 15:56
 */
@Slf4j
public class SignUtil {


    /**
     * @param treeMap
     * @param appSecret
     * @param api
     * @return
     */
    public static String pd(Map<String, Object> treeMap, String appKey, String appSecret, String api) {
        try {
            treeMap.put("type", api);
            treeMap.put("app_key", appKey);
            treeMap.put("timestamp", System.currentTimeMillis() / 1000);
            // 生成要签名的字符串
            StringBuilder signText = new StringBuilder();
            treeMap.entrySet().forEach(entry -> {
                if(isSimpleValueType(entry.getValue().getClass())){
                    signText.append(entry.getKey()).append(entry.getValue());
                }else {
                    signText.append(entry.getKey()).append(JsonUtil.toJson(entry.getValue()));
                }
            });
            // 进行256加密
            String s = appSecret + signText + appSecret;
            return Func.md5Hex(s).toUpperCase();
        } catch (Exception e) {
            log.error("pdd加签失败", e);
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param pddCommonDTO
     * @param appSecret
     * @return
     */
    public static String pd2(PddCommonDTO pddCommonDTO, String appSecret) {
        try {
            Map<String, Object> map = JsonUtil.toMap(JsonUtil.toJson(pddCommonDTO));
            TreeMap<String, Object> treeMap = new TreeMap<>(map);
            // 生成要签名的字符串
            StringBuilder signText = new StringBuilder();
            treeMap.entrySet().forEach(entry -> {
                if(isSimpleValueType(entry.getValue().getClass())){
                    signText.append(entry.getKey()).append(entry.getValue());
                }else {
                    signText.append(entry.getKey()).append(JsonUtil.toJson(entry.getValue()));
                }
            });
            // 进行256加密
            String s = appSecret + signText + appSecret;
            return Func.md5Hex(s).toUpperCase();
        } catch (Exception e) {
            log.error("pdd加签失败", e);
            throw new RuntimeException(e);
        }
    }
}
